# -*- codeing = utf-8 -*-
# @Time : 2024/4/24 23:14
# @Author : huangjing
# @File : myCell.py
# @Software : PyCharm
import mindspore
from mindspore import nn, ops
from mindspore.dataset import vision, transforms
from mindspore.dataset import MnistDataset
# Download data from open datasets
from download import download
#获取数据集
# url = "https://mindspore-website.obs.cn-north-4.myhuaweicloud.com/" \
#       "notebook/datasets/MNIST_Data.zip"
# path = download(url, "./", kind="zip", replace=True)
def datapipe(path, batch_size):
    image_transforms = [
        vision.Rescale(1.0 / 255.0, 0),
        vision.Normalize(mean=(0.1307,), std=(0.3081,)),
        vision.HWC2CHW()
    ]
    label_transform = transforms.TypeCast(mindspore.int32)
    dataset = MnistDataset(path)
    dataset = dataset.map(image_transforms, 'image')
    dataset = dataset.map(label_transform, 'label')
    dataset = dataset.batch(batch_size)
    return dataset

train_dataset = datapipe('MNIST_Data/train', batch_size=64)
test_dataset = datapipe('MNIST_Data/test', batch_size=64)
epochs = 3
batch_size = 64
learning_rate = 1e-2
#构建神经网络
class Network(nn.Cell):
    def __init__(self):
        super().__init__()
        self.flatten = nn.Flatten()
        self.dense_relu_sequential = nn.SequentialCell(
            nn.Dense(28*28,512,weight_init='normal',bias_init='zeros'),
            nn.ReLU(),
            nn.Dense(512,512,weight_init='normal',bias_init='zeros'),
            nn.ReLU(),
            nn.Dense(512,10,weight_init='normal',bias_init='zeros'),
        )
    def construct(self,x):
        x = self.flatten(x)
        logits = self.dense_relu_sequential(x)
        return logits
model = Network()
#定义损失函数
loss_fn = nn.CrossEntropyLoss()
#定义优化器
optimizer = nn.SGD(model.trainable_params(), learning_rate=learning_rate)
#定义函数
def forward_fn(data,label):
    logits = model(data)
    loss = loss_fn(logits,label)
    return loss,logits
#获取微分函数
grad_fn = mindspore.value_and_grad(forward_fn,None,optimizer.parameters,has_aux=True)
#将微分函数和优化器封装起来
def train_step(data,label):
    (loss,_),grads = grad_fn(data,label)
    optimizer(grads)
    return loss
#训练
def train_loop(model,dataset):
    size = dataset.get_dataset_size()
    model.set_train()
    for batch, (data, label) in enumerate(dataset.create_tuple_iterator()):
        loss = train_step(data, label)
        if batch % 100 == 0:
            loss, current = loss.asnumpy(), batch
            print(f"loss: {loss:>7f}  [{current:>3d}/{size:>3d}]")
#测试
def tes_loop(model, dataset, loss_fn):
    num_batches = dataset.get_dataset_size()
    model.set_train(False)
    total, test_loss, correct = 0, 0, 0
    for data, label in dataset.create_tuple_iterator():
        pred = model(data)
        total += len(data)
        test_loss += loss_fn(pred, label).asnumpy()
        correct += (pred.argmax(1) == label).asnumpy().sum()
    test_loss /= num_batches
    correct /= total
    print(f"Test: \n Accuracy: {(100*correct):>0.1f}%, Avg loss: {test_loss:>8f} \n")

for t in range(epochs):
    print(f"Epoch {t+1}\n-------------------------------")
    train_loop(model, train_dataset)
    tes_loop(model, test_dataset, loss_fn)
print("Done!")